import configparser
from pathlib import Path

BASE_DIR = Path(__file__).parent.parent.absolute()

config = configparser.ConfigParser()
config.read(BASE_DIR / 'config.ini')


def try_get(section, option, default=None):
    try:
        return config.get(section, option)
    except (configparser.NoOptionError, configparser.NoSectionError):
        return default


class Config:

    DEBUG = True
    SECRET_KEY = 'S02sI%h3xjdh39^5sb2#323 ^s52(#@'

    JSON_AS_ASCII = False

    THUMB_WIDTH = 200  # 缩略图固定宽度
    WEBP_QUALITY = 90  # webp图片质量

    # 数据库 mysql
    # SQLALCHEMY_DATABASE_URI = "mysql+pymysql://{user}:{pw}@{host}:{port}/{db}".format(
    #     user=try_get('database', 'user'),
    #     pw=try_get('database', 'pass'),
    #     host=try_get('database', 'host'),
    #     port=try_get('database', 'port'),
    #     db=try_get('database', 'db')
    # )
    # 数据库 sqlite
    SQLALCHEMY_DATABASE_URI = f'sqlite:///{(BASE_DIR /'piclab.db').as_posix()}'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = False

    # redis 用作队列
    REDIS_URL = try_get('redis', 'uri')

    # Celery
    CELERY_BROKER_URL = try_get('celery', 'uri')
    CELERY_RESULT_BACKEND = try_get('celery', 'uri')
    CELERYD_MAX_TASKS_PER_CHILD = 10
    # CELERY_ACCEPT_CONTENT = ['json']

    # Pic Path
    FILE_PATH = Path(try_get('file', 'path'))  # 文件根目录
    PICLAB_BASE_DIR = FILE_PATH / 'pic'
    PICLAB_THUMBNAIL_DIR = FILE_PATH / 'sm'
    PICLAB_TEMP_DIR = FILE_PATH / 'temp'
    PICLAB_THUMB_TEMP_DIR = FILE_PATH / 'thumb_temp'
    PICLAB_RECYCLE_DIR = FILE_PATH / 'recycle'

    # 图片链接
    IMAGE_HOST_1 = try_get('image_host', 'host_1')
    IMAGE_HOST_2 = try_get('image_host', 'host_2')
    IMAGE_API_1 = try_get('image_host', 'api_1')
    IMAGE_API_2 = try_get('image_host', 'api_2')


for path in (Config.PICLAB_BASE_DIR, Config.PICLAB_THUMBNAIL_DIR, Config.PICLAB_TEMP_DIR, Config.PICLAB_THUMB_TEMP_DIR, Config.PICLAB_RECYCLE_DIR):
    if not path.exists():
        path.mkdir()
